package neu.dreamera.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.utils.CoordinateConverter;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.util.HashMap;

import neu.dreamera.R;
import neu.dreamera.utils.HttpConnectionUtil;

/**
 * Created by root on 16-7-1.
 */
public class AddPictureActivity extends Activity {

    private final static String TAG="AddPictureActivity";

    private EditText picture_title_EditText;

    private EditText picture_datetime_EditText;
    private Spinner picture_datetime_Spinner;
    private EditText picture_time_str_EditText;
    private EditText picture_like_count_EditText;
    private EditText picture_detail_url_EditText;
    private TextView picture_location_TextView;
    private EditText picture_detail_title_EditText;
    private Button clear;
    private Button submit;
    private ImageView picture_imageview;

    private Bitmap picture_map;

    private String picture_title;
    private String picture_longitude;
    private String picture_latitude;
    private int point_id;
    File file;
    Uri uri;
    private String file_path;

    private HashMap<String, SoftReference<Bitmap>> mImageCache;


    HashMap<String,Object> pic_map=new HashMap<String, Object>();

    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        Log.d(TAG,"onCreate");
        setContentView(R.layout.picture_add_activity);
        //bind
        picture_imageview= (ImageView) findViewById(R.id.picture_show);
        picture_title_EditText= (EditText) findViewById(R.id.picture_title);
        picture_datetime_EditText= (EditText) findViewById(R.id.picture_datetime);
        picture_datetime_Spinner= (Spinner) findViewById(R.id.picture_datetime_Spinner);
        picture_time_str_EditText= (EditText) findViewById(R.id.picture_time_str);
        picture_like_count_EditText= (EditText) findViewById(R.id.picture_like_count);
        picture_detail_url_EditText= (EditText) findViewById(R.id.picture_detail_url);
        picture_location_TextView= (TextView) findViewById(R.id.picture_location);
        picture_detail_title_EditText= (EditText) findViewById(R.id.picture_detail_title);
        submit= (Button) findViewById(R.id.submit);
        clear= (Button) findViewById(R.id.clear);


       // picture_datetime_Spinner.set

        //get and set data
        Intent intent=getIntent();
        Bundle bundle=intent.getExtras();
        point_id=bundle.getInt("point_id");
        file_path=bundle.getString("picture_path");
        picture_longitude=bundle.getString("longitude");
        picture_latitude=bundle.getString("latitude");

        //get picture
        file=new File(file_path);

        Log.d(TAG,"the file_path is:"+file_path);
        Log.d(TAG,"the file name is:"+file.getName());
        InputStream is=null;
        if(file.exists()){
            Log.d(TAG,"file exits");
        }
        try {
            is=new FileInputStream(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }


        picture_map= BitmapFactory.decodeStream(is);
        Log.d(TAG,"the picture_map is :"+picture_map.getByteCount());
        Log.d(TAG,"the height and the width is"+picture_map.getHeight()+","+picture_map.getWidth());
        Log.d(TAG,"the picture_map is "+picture_map);
        Log.d(TAG,"set picture to imageView");
        picture_imageview.setImageBitmap(picture_map);
    }




    @Override
    protected void onStart(){
        super.onStart();
        Log.d(TAG,"onStart");
    }
    @Override
    protected void onResume() {
        super.onResume();
        Log.d(TAG, "onResume");


        LatLng sourceLatLng=new LatLng(Double.parseDouble(picture_latitude),Double.parseDouble(picture_longitude));
        // 将GPS设备采集的原始GPS坐标转换成百度坐标
        CoordinateConverter converter  = new CoordinateConverter();
        converter.from(CoordinateConverter.CoordType.GPS);
        // sourceLatLng待转换坐标
        converter.coord(sourceLatLng);
        LatLng desLatLng = converter.convert();


        picture_location_TextView.setText(desLatLng.longitude+"\n"+desLatLng.latitude);


        picture_datetime_Spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view,
                                       int pos, long id) {

               String[] languages = getResources().getStringArray(R.array.languages);
                picture_datetime_EditText.setText(languages[pos]);
               // Toast.makeText(AddPictureActivity.this, "你点击的是:"+languages[pos],Toast.LENGTH_LONG).show();
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                // Another interface callback
            }
        });




        submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.d(TAG,"start upload picture ");

                file=new File(file_path);
                Log.d(TAG,"file name is"+file.getName());
                String filename=file.getName();
/*
                File file=new File(file_path);//创建文件对象
                try {
                    //file.createNewFile();//创建新文件
                    Log.d(TAG,"the new file created!");
                    FileOutputStream fileOS=new FileOutputStream(file);//创建文件输出流对象
                    picture_map.compress(Bitmap.CompressFormat.PNG, 100,fileOS);//把图片内容压缩为JPEG格式输出到输出流对象，可设置压缩质量0-100
                    Log.d(TAG,"picture_map is ok!");
                    Log.d(TAG,"the file name is "+file.getName());
                    pic_map.put("picture",picture_map.toString());
                    fileOS.flush();//将缓冲区数据全部写道输出流中
                    fileOS.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
*/
                /*
                file_path=getRealFilePath(AddPictureActivity.this,uri);
                file=new File(String.valueOf(uri));
                Log.d(TAG,"file path is "+file_path);
                Log.d(TAG,"the file is "+file);
                Log.d(TAG,"the file name is "+file.getName());
                */
/*
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                picture_map.compress(Bitmap.CompressFormat.PNG, 40, baos);
                try {
                    baos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                byte[] buffer = baos.toByteArray();
                System.out.println("图片的大小："+buffer.length);
                //将图片的字节流数据加密成base64字符输出
                String photo = Base64.encodeToString(buffer, 0, buffer.length,Base64.DEFAULT);
*/
                pic_map.put("title",picture_title_EditText.getText().toString());
                pic_map.put("picture",file);
                pic_map.put("datetime",picture_datetime_EditText.getText().toString()+"-01-01T01:01:00Z");
                pic_map.put("time_str",picture_time_str_EditText.getText().toString());
                pic_map.put("detail_url",picture_detail_url_EditText.getText().toString());
                pic_map.put("detail_title",picture_detail_title_EditText.getText().toString());
                pic_map.put("like_count",picture_like_count_EditText.getText().toString());
                pic_map.put("longitude",picture_longitude);
                pic_map.put("latitude",picture_latitude);
                pic_map.put("altitude",0);
                pic_map.put("place",point_id);

                Log.d(TAG,"pic_map is "+pic_map.toString());

                new AlertDialog.Builder(AddPictureActivity.this).setTitle("系统提示")//设置对话框标题
                        .setMessage("ADD this picture?")//设置显示的内容
                        .setPositiveButton("Yes", new DialogInterface.OnClickListener() {//添加确定按钮
                            @Override
                            public void onClick(DialogInterface dialog, int which) {//确定按钮的响应事件
                                //new thread to add
                                new Thread() {
                                    public void run() {
                                        try{
                                            HttpConnectionUtil.doPost(HttpConnectionUtil.PICTUREURL,pic_map);
                                            runOnUiThread(new Runnable() {
                                                @Override
                                                public void run() {
                                                    if (HttpConnectionUtil.result == "success") {
                                                        Toast.makeText(AddPictureActivity.this, "Add picture success!", Toast.LENGTH_SHORT).show();
                                                       // pic_map.clear();
                                                    }
                                                    else{
                                                        Toast.makeText(AddPictureActivity.this, "Add picture faile!", Toast.LENGTH_SHORT).show();
                                                       //pic_map.clear();
                                                    }
                                                }
                                            });
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                        }
                                    }
                                }.start();
                            }
                        })
                        .setNegativeButton("No", new DialogInterface.OnClickListener() {//添加返回按钮
                            @Override
                            public void onClick(DialogInterface dialog, int which) {//响应事件
                                // TODO Auto-generated method stub
                                dialog.dismiss();
                            }
                        }).show();//在按键响应事件中显示此对话框
            }
        });
        clear.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view) {
                picture_title_EditText.setText("");
                picture_datetime_EditText.setText("");
                picture_time_str_EditText.setText("");
                picture_detail_url_EditText.setText("");
                picture_detail_title_EditText.setText("");
                picture_like_count_EditText.setText("");
            }
        });


    }
    @Override
    protected void onPause(){
        super.onPause();
        Log.d(TAG,"onPause");
    }
    @Override
    protected void onStop(){
        super.onStop();
        Log.d(TAG,"onStop");
    }
    @Override
    protected void onDestroy(){
        super.onDestroy();
        Log.d(TAG,"onDestroy");
        if(!picture_map.isRecycled()){
            picture_map.recycle();
        }
    }
    @Override
    protected void onRestart(){
        super.onRestart();
        Log.d(TAG,"onRestart");
    }

    /**
     * Try to return the absolute file path from the given Uri
     *
     * @param context
     * @param uri
     * @return the file path or null
     */
    public static String getRealFilePath(final Context context, final Uri uri ) {
        if ( null == uri ) return null;
        final String scheme = uri.getScheme();
        String data = null;
        if ( scheme == null )
            data = uri.getPath();
        else if ( ContentResolver.SCHEME_FILE.equals( scheme ) ) {
            data = uri.getPath();
        } else if ( ContentResolver.SCHEME_CONTENT.equals( scheme ) ) {
            Cursor cursor = context.getContentResolver().query( uri, new String[] { MediaStore.Images.ImageColumns.DATA }, null, null, null );
            if ( null != cursor ) {
                if ( cursor.moveToFirst() ) {
                    int index = cursor.getColumnIndex( MediaStore.Images.ImageColumns.DATA );
                    if ( index > -1 ) {
                        data = cursor.getString( index );
                    }
                }
                cursor.close();
            }
        }
        return data;
    }
    private File GetSureFile(String path){
        File temp_file=new File(path);
        String rootPath = "/";
        while(temp_file.isDirectory()){
        }
        return temp_file;
    }
}
